package com.hcms.admin.service.impl;

import com.hcms.admin.service.ISysAdminCacheService;
import com.hcms.common.service.IRedisService;
import com.hcms.mybatis.entity.SysAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
public class SysAdminCacheServiceImpl implements ISysAdminCacheService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${redis.database}")
    private String REDIS_DATABASE;

    @Value("${redis.key.admin}")
    private String REDIS_KEY_ADMIN;

    @Value("${redis.key.permission}")
    private String REDIS_KEY_PERMISSION;

    @Value("${redis.expire.common:7200}")
    private Long REDIS_EXPIRE;

    @Autowired
    private IRedisService redisService;

    @Override
    public SysAdmin getAdminByUsername(String username) {
        logger.info("Run getAdmin(), username={}", username);
        String key = REDIS_DATABASE + ":" + REDIS_KEY_ADMIN + ":" + username;
        return (SysAdmin) redisService.get(key);
    }

    @Override
    public void setAdmin(SysAdmin admin) {
        logger.info("Run setAdmin(), username={}", admin.getUsername());
        String key = REDIS_DATABASE + ":" + REDIS_KEY_ADMIN + ":" + admin.getUsername();
        redisService.set(key, admin, REDIS_EXPIRE);
    }

    @Override
    public void delAdmin(String username) {
        logger.info("Run delAdmin(), username={}", username);
        String key = REDIS_DATABASE + ":" + REDIS_KEY_ADMIN + ":" + username;
        redisService.del(key);
    }

    @Override
    public Collection<String> getPermissionAdminId(Long adminId) {
        logger.info("Run getPermission(), admin={}", adminId);
        String key = REDIS_DATABASE + ":" + REDIS_KEY_PERMISSION + ":" + adminId;
        return (Collection<String>) redisService.get(key);
    }

    @Override
    public void setPermission(Long adminId, Collection<String> permission) {
        logger.info("Run setPermission(), admin={}", adminId);
        String key = REDIS_DATABASE + ":" + REDIS_KEY_PERMISSION + ":" + adminId;
        redisService.set(key, permission, REDIS_EXPIRE);
    }

    @Override
    public void delPermission(Long adminId) {
        logger.info("Run delPermission(), admin={}", adminId);
        String key = REDIS_DATABASE + ":" + REDIS_KEY_PERMISSION + ":" + adminId;
        redisService.del(key);
    }
}
